# -*- conding:UTF-8 -*-

'''
@ Project: p7_flask
@ File: comments.py
@ Author: 师路遥
@ Date：2022/6/7 0:48

'''
import json
from flask import Blueprint,jsonify,g
from flask_restful import Api,reqparse,Resource,marshal

from models.user import *
from common.model_fields.comment_fields import comments_fields
from common.model_fields.comment_fields import basic_fields
from common.model_fields.user import *

comment_bp = Blueprint('comment',__name__,url_prefix='/comments')

api = Api(comment_bp)

class CommentResource(Resource):
    def get(self,nid):
        """
        获取所有的评论
        1. 接收前端传来的文章id
        2. 获取这个文章的所有评论
            1. 判断评论有没有被回复
            2. 若有回复, 获取回复的评论内容
        3. 返回的数据格式
        {
            "nid":nid,
            'comments':[
                {
                    "cid": 1,
                    "content": '我冲突皮哦按来的',
                    'user_info":{
                        'uid':1,
                        'name':'张三',
                        'img':''
                    },
                    "child_comments":[
                        {
                            "cid": 1,
                            "content": '我冲突皮哦按来的',
                            'user_info":{
                                'uid':1,
                                'name':'张三',
                                'img':''
                            },
                        },
                        ....
                    ]
                }
                .....
            ]

        }
        """
        comments = Comment.query.filter_by(article_id=nid).all()
        if not comments:
            # 说明文章没有评论
            return jsonify(message='获取评论成功', data=[], code=200)
        comments_dict = json.loads(json.dumps(marshal(comments, comments_fields)))
        print('评论的字典数据>>', comments_dict)
        for comment in comments_dict:
            user = UserModel.query.filter_by(uid=comment['user_id']).first()
            comment['user_info'] = {
                'uid': user.uid,
                'uname': user.uname,
                'profile_photo': user.profile_photo
            }
            # 判断文章是否有回复
            is_reply_comment = comment['parent_id']
            # 回复评论的数据
            child_comment = []
            if is_reply_comment:
                # 有回复,
                # TODO 获取回复的评论内容及用户信息
                comments = Comment.query.filter_by(cmid=comment['parent_id']).all()
                comments_dict = json.loads(json.dumps(marshal(comments, comments_fields)))
                for comment in comments_dict:
                    # 获取评论的用户id, 获取用户信息
                    user = UserModel.query.filter_by(uid=comment['user_id']).first()
                    comment['user_info'] = {
                        'uid': user.uid,
                        'uname': user.uname,
                        'profile_photo': user.profile_photo
                    }
            else:
                # 没有回复
                comment['child_comment'] = child_comment
        return jsonify(message='获取评论成功', code=200, data=comments_dict)

    def post(self,nid):
        uid = g.user_id
        parser = reqparse.RequestParser()
        parser.add_argument('content')
        parser.add_argument('parent_id')
        args = parser.parse_args()
        content = args.get('contend')
        parent_id = args.get('parent_id')

        try:
            comment = Comment(user_id=uid,article_id=nid,parent_id=parent_id,content=content)
            db.session.add(comment)
            db.session.commit()
        except Exception as e:
            print(e)
            return jsonify(message='评论失败',code=400)
        return jsonify(message='评论成功',code=200)

# 文章的查询，添加
class SeallAdd(Resource):
    def get(self):
        basec = News.query.all()
        data = marshal(basec,basic_fields)
        return data

    def post(self):
        # uid = g.user_id
        parser = reqparse.RequestParser()
        args_list = ['uid','channel_id','title','content']
        for i in args_list:
            parser.add_argument(i)
        args = parser.parse_args()
        uid = args.get('uid')
        channel_id = args.get('channel_id')
        title = args.get('title')
        content = args.get('content')

        if not all([uid,channel_id,title,content]):
            return jsonify(message='请完善信息',code=400)

        chan = Channel.query.filter_by(cid=channel_id).first()
        if not chan:
            return jsonify(message='频道不存在',code=400)

        try:
            news = News(user_id=uid,channel_id=channel_id,content=content,title=title)
            db.session.add(news)
            db.session.commit()
        except Exception as e:
            print(e)
            return jsonify(message='添加咨询失败',code=500)
        else:
            return jsonify(message='添加咨询成功',code=200)

# 文章的检索，修改，删除
class SelPutDel(Resource):
    def get(self,id):
        news = News.query.filter_by(nid=id).first()
        if not news:
            return jsonify(message='没有该文章',code=400)
        else:
            news_status = news.status
            print('文章状态>>>>>>>>>>>',news_status)
            if news_status == 4:
                return jsonify(message='该文章已经删除',code=400)
            data = marshal(news,basic_fields)
            return data

    def put(self,id):
        parser = reqparse.RequestParser()
        parser.add_argument('title')
        parser.add_argument('content')
        args = parser.parse_args()
        content = args.get('content')
        title = args.get('title')

        if title:
            News.query.filter_by(nid=id).update({'title':title})
        if content:
            News.query.filter_by(nid=id).update({'content': content})
        db.session.commit()

        return jsonify(message='更新成功', code=200)

    def delete(self,id):
        news = News.query.filter_by(nid=id).first()
        if not news:
            return jsonify(message='没有该文章',code=400)

        try:
            News.query.filter_by(nid=id).update({'status':4})
            db.session.commit()
            return jsonify(message='删除成功', code=200)
        except Exception as e:
            print(e)
            return jsonify(message='删除失败', code=400)

# 获取文章
class Detail(Resource):
    def get(self,id):
        news = News.query.filter_by(nid=id).first()
        data = json.loads(json.dumps(marshal(news,news_fields)))
        user = UserModel.query.filter_by(uid=news.user_id).first()
        data['nick_name'] = user.uname

        comment_data = [{
            'id':i.cmid,
            'art_id':i.article_id,
            'like_count':i.like_count,
            'reply_count':i.reply_count,
            'content':i.content,
            'comment_length':len(news.comment)
        }for i in news.comment]

        data['comment'] = comment_data
        return jsonify(message='获取文章成功',code=200,data=data)


api.add_resource(Detail,'/detail/<int:id>')
api.add_resource(SelPutDel,'/new/<int:id>')
api.add_resource(SeallAdd,'/new')
api.add_resource(CommentResource,'/all/<int:nid>')
